package com.bsj.travel.util;

import com.bsj.travel.def.common.DO.ProductTopicDO;
import com.bsj.travel.def.mqtt.auth.MqttSignature;
import org.springframework.beans.BeanUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author yinhao
 * @version 1.0
 * @description 产品主题常用方法
 * @date 2023/11/23
 */
public class ProductTopicUtil {

    /**
     * 批量替换主题中的产品key
     * @param productKey
     * @param productTopicDOS
     * @return
     */
    public static Set<ProductTopicDO> addTopic(String productKey, List<ProductTopicDO> productTopicDOS) {
        Set<ProductTopicDO> set = new HashSet<>();
        productTopicDOS.stream().forEach(item -> {
            String topicClass = StringUtils.replaceProduct(item.getTopicClass(), productKey);
            ProductTopicDO topicDO = new ProductTopicDO();
            BeanUtils.copyProperties(item, topicDO);
            topicDO.setTopicClass(topicClass);
            set.add(topicDO);
        });
        return set;
    }

    /**
     * 校验产品主题是否权限正确
     * @param mqttAuth 鉴权对象
     * @param data 主题信息
     * @param topic 待验证主题
     * @param purview 1发布  2订阅  3发布订阅 (移除相反权限的的类型)
     * @return
     */
    public static AtomicReference<Boolean> isValidTopic(MqttSignature mqttAuth, List<ProductTopicDO> data,
                                                 String topic, Integer purview) {
        // 校验客户端订阅的topic，校验成功返回true，失败返回false
        var productKey = mqttAuth.getProductKey();
        var deviceName = mqttAuth.getDeviceName();
        //移除权限为订阅权限的topic信息
        boolean removeIf = data.removeIf((ProductTopicDO po) -> po.getPurview().equals(purview));
        //判断当前主题是否具有发布权限
        AtomicReference<Boolean> perm = new AtomicReference<>(false);
        data.stream().forEach(item -> {
            //将通配主题符替换成唯一设备主题
            String topicClass = item.getTopicClass();
            String srcTopic = StringUtils.replaceDevice(topicClass, deviceName);
            Boolean matchTopic = StringUtils.matchTopic(srcTopic, topic, productKey);
            if (matchTopic) {
                perm.set(true);
                return;
            }
//            Boolean b = StringUtils.matchTopicForDevName(item.getTopicClass(), mqttAuth.getDeviceName(), topic);
//            if (b) {
//                perm.set(true);
//                return;
//            }
        });
        return perm;
    }
}
